package com.taptech.doufu.weex.module;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.taobao.weex.annotation.JSMethod;
import com.taobao.weex.bridge.JSCallback;
import com.taobao.weex.common.WXModule;
import com.taobao.weex.common.WXModuleAnno;
import com.taptech.doufu.alipay.AliPayActivity;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.bean.AlbumsBean;
import com.taptech.doufu.bean.DFHomeBannerBean;
import com.taptech.doufu.bean.HomeTopBean;
import com.taptech.doufu.bean.ShareBeansInfo;
import com.taptech.doufu.bean.TagsBean;
import com.taptech.doufu.bean.cartoon.CartoonBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.constant.GlobalConfig;
import com.taptech.doufu.db.history.Read_DataBaseUtil;
import com.taptech.doufu.db.history.Read_HirstoryUtil;
import com.taptech.doufu.db.offline.OffLineDataBaseUtil;
import com.taptech.doufu.event.EventBusChangeTheme;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.listener.ILoginCallback;
import com.taptech.doufu.listener.UploadImageListener;
import com.taptech.doufu.manager.NovelEditManager;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.services.CartoonServices;
import com.taptech.doufu.services.HomeMainServices;
import com.taptech.doufu.services.PersonalNoteService;
import com.taptech.doufu.services.history.ReadHistoryUtil;
import com.taptech.doufu.services.history.ReadRecord;
import com.taptech.doufu.services.offline.OffLineInfoBean;
import com.taptech.doufu.services.offline.OffLineService;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.services.personalcenter.QQService;
import com.taptech.doufu.services.personalcenter.WeChatService;
import com.taptech.doufu.services.personalcenter.WeiboService;
import com.taptech.doufu.ui.activity.BrowseActivity;
import com.taptech.doufu.ui.activity.MainHomeActivity;
import com.taptech.doufu.ui.activity.MoreSetActivity;
import com.taptech.doufu.ui.activity.MySpeakerActivity;
import com.taptech.doufu.ui.activity.MyWorksActivity;
import com.taptech.doufu.ui.activity.NewCpDesActivity;
import com.taptech.doufu.ui.activity.NewNovelCreateListTosActivity;
import com.taptech.doufu.ui.activity.NovelCreateTosActivity;
import com.taptech.doufu.ui.activity.NovelDesToCommActivity;
import com.taptech.doufu.ui.activity.NovelDesToDetailActivity;
import com.taptech.doufu.ui.activity.NovelDetailsActivity;
import com.taptech.doufu.ui.activity.NovelSectionDetailsActivity;
import com.taptech.doufu.ui.activity.PersonalAttentionsActivity;
import com.taptech.doufu.ui.activity.PersonalFansActivity;
import com.taptech.doufu.ui.activity.PersonalNewDynamicActivity;
import com.taptech.doufu.ui.activity.PersonalPointsActivity;
import com.taptech.doufu.ui.activity.PersonalSendLetterActivity;
import com.taptech.doufu.ui.activity.ShowPicActivity;
import com.taptech.doufu.ui.activity.SweepFlowerActivity;
import com.taptech.doufu.ui.activity.UserDetailActivity;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.ui.activity.story.StoryDetailsActivity;
import com.taptech.doufu.ui.activity.weex.DialogWeexActivity;
import com.taptech.doufu.ui.activity.weex.StartWeexActivityUtils;
import com.taptech.doufu.ui.activity.weex.TFWXActivity;
import com.taptech.doufu.ui.adapter.DfhomeNovelAdapter3;
import com.taptech.doufu.ui.dialog.PermissionTipDialog;
import com.taptech.doufu.ui.view.FlowerDialogManager;
import com.taptech.doufu.ui.view.GiftDialogManager;
import com.taptech.doufu.ui.view.ImageUtil;
import com.taptech.doufu.ui.view.ShareTopPopupWindow;
import com.taptech.doufu.umeng.UVerifyManager;
import com.taptech.doufu.util.AesUtil;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.ImageManager;
import com.taptech.doufu.util.PackageUtils;
import com.taptech.doufu.util.ScreenUtil;
import com.taptech.doufu.util.ShareUtil;
import com.taptech.doufu.util.ShareUtils;
import com.taptech.doufu.util.StartActivityUtil;
import com.taptech.doufu.util.StartActivityUtils;
import com.taptech.doufu.util.TMAnalysis;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.util.image.ImagePickUtil;
import com.taptech.doufu.weex.QLXApplicationUtil;
import com.taptech.doufu.weex.QLXGlobal;
import com.taptech.doufu.weex.QLXStringUtil;
import com.taptech.doufu.weex.keyboard.QLXKeyBoard;
import com.taptech.doufu.weex.statusbar.StatusBarCompatFlavorRom;
import com.douhuayuedu.douhua.wxapi.WXEntryActivity;
import com.douhuayuedu.douhua.wxapi.WeixinService;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by qlx on 2016/12/10.
 */




public class TFBridgeMoule extends WXModule implements HttpResponseListener{


    final static int TFAtResult = 12;


    public enum TFBridgeType {
        TFBridgeTypeDynamic(0), // 根据param字典 动态打开
        TFBridgeTypeFlower(1), // 献花
        TFBridgeTypeReward(2),// 打赏
        TFBridgeTypeNovelCatelog(3),// 小说目录
        TFBridgeTypeNovelComment(4),// 小说评论
        TFBridgeTypeUserCenter(5),// 用户个人中心
        TFBridgeTypeLoginIfNeed(6),// 没登录打开登录页面
        TFBridgeTypeReadNovel(7),// 进入小说阅读
        TFBridgeTypeShare(8),// 分享
        TFBridgeTypeDownloadNovel(9),// 下载小说
        TFBridgeTypeNovelReview(10),// 文评
        TFBridgeTypeController(11),// 打开控制器
        TFBridgeTypeUserChapterList(12),// 用户小说章节列表
        TFBridgeTypeStatusBarLight(13),// 状态栏边成白色
        TFBridgeTypeStatusBarDark(14),// 状态栏边成黑色
        TFBridgeTypeAtAllowUser(15),// at选择关注人页面
        TFBridgeTypeWeb(16),// 打开web页面

        TFBridgeTypePublishProduction(17),//发布作品/日常
        TFBridgeTypeMyActivity(18), //我的动态
        TFBridgeTypeMyFans(19), //我的粉丝
        TFBridgeTypeMyAttentions(20), //我的关注
        TFBridgeTypePublishBBS(21), //小喇叭
        TFBridgeTypeMyBean(22), //我的豆子
        TFBridgeTypePersonalInfo(23), //个人信息页面----->已改成weex面
        TFBridgeTypeSetting(24), //设置
        TFBridgeTypeNotifyPage(25), //系统通知页面

        TFBridgeTypePrivateMsgList(26),  //私信列表
        TFBridgeTypePrivateMsg(27),  //与某人私信
        TFBridgeTypeCartoonDetail(28), //漫画详情
        TFBridgeTypeNomalDetail(29),//日常详情
        TFBridgeTypeNovelSweepDetail(30), //文评详情
        TFBridgeTypeMyGroupNotice(31),//群组聊天
        TFBridgeTypeGame(32), //分享新接口
        TFBridgeTypeReadComic(33),
        TFBridgeTypeAlbums(34),//专辑
        TFBridgeTypeCreateNovel(35),//新建小说
        TFBridgeTypeBanner(36),//点击轮播图跳转
        TFBridgeTypeTag(37),//标签
        TFBridgeTypeMore(38);//点击"更多"跳转

        private int value = 0;

        TFBridgeType(int value) {
            this.value = value;
        }

        public int getValue() {
            return this.value;
        }
        }

    private static  String mArticleId;
    private static  String mArticleTitle = "";

    @WXModuleAnno(moduleMethod = true,runOnUIThread = true)
    public void reloadWeex(){

    }

    @WXModuleAnno(moduleMethod = true,runOnUIThread = true)
    public void openPage(String jsonParam , final JSCallback callback){

        try {
            if (jsonParam instanceof String){
                JSONObject param = JSON.parseObject(jsonParam);
                TFBridgeType type = TFBridgeType.values()[param.getInteger("id")];
                JSONObject pageParam = null;
                if ((param.containsKey("param"))){
                   Object temp  =   param.get("param");
                    if (temp instanceof JSONObject){
                        pageParam = (JSONObject)temp;
                    }else if(temp instanceof String){
                        JSONObject jon = new JSONObject();
                        jon.put("url",temp);
                        pageParam = jon;
                    }

                }
                switch (type){
                    case TFBridgeTypeDynamic:
                    {
                        this.jumpToDynamic(pageParam);
                        break;
                    }
                    case TFBridgeTypeNovelCatelog:
                    {
                        this.jumpToNovelCatalog(pageParam);
                        break;
                    }
                    case TFBridgeTypeNovelComment:
                    {
                        this.jumpToComment(pageParam);
                        break;
                    }
                    case TFBridgeTypeUserCenter:
                    {
                        this.jumpToPersonalCenter(pageParam);
                        break;
                    }
                    case TFBridgeTypeLoginIfNeed:
                    {
                        if (AccountService.getInstance().isLogin()){
                            this.uid(callback);
                        }else {
                            AccountService.getInstance().jumpToLogin();
                        }
                        break;
                    }
                    case TFBridgeTypeReadNovel:
                    {
                        this.jumpToNovel(pageParam);
                        break;
                    }
                    case TFBridgeTypeBanner:
                        bannerJump(pageParam);
                        break;
                    case TFBridgeTypeMore:
                        moreJump(pageParam);
                        break;
                    case TFBridgeTypeAlbums:
                        jumpToAlbums(pageParam);
                        break;
                    case TFBridgeTypeCreateNovel:
                        Intent intentCreateNovel = new Intent(mWXSDKInstance.getContext(), NovelCreateTosActivity.class);
                        mWXSDKInstance.getContext().startActivity(intentCreateNovel);
                        break;
                    case TFBridgeTypeUserChapterList:
                    {
                        this.jumpToNovelChanpterList(pageParam);
                        break;
                    }
                    case TFBridgeTypeShare:
                    {
                        JSONObject object = pageParam.getJSONObject("object");
                        if (object!=null && object.containsKey("object_type")&&
                                Constant.OBJECT_TYPE_CARTOON == object.getInteger("object_type")) {
                            this.jumpToCartoonShare(pageParam);
                        }else{
                            this.jumpToNovelShare(pageParam);
                        }
                        break;
                    }
                    case TFBridgeTypeDownloadNovel:
                    {
                        this.jumpToDownloadNovel(pageParam);
                        break;
                    }
                    case TFBridgeTypeFlower:
                    {
                        this.jumpToFlower(pageParam);
                        break;
                    }
                    case TFBridgeTypeReward:
                    {
                        this.jumpToReward(pageParam);
                        break;
                    }case TFBridgeTypeStatusBarLight:
                    {
                        try {
                                TFWXActivity activity = (TFWXActivity ) mWXSDKInstance.getContext();
                                StatusBarCompatFlavorRom.setLightStatusBar(activity, false);

                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        break;
                    }
                    case TFBridgeTypeStatusBarDark:
                    {
                        try {
                            TFWXActivity activity = (TFWXActivity ) mWXSDKInstance.getContext();
                            StatusBarCompatFlavorRom.setLightStatusBar(activity, true);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        break;
                    }
                    case TFBridgeTypeAtAllowUser:
                       this.handleAtUser(callback);
                        break;
                    case TFBridgeTypeWeb:
                        if (pageParam.containsKey("needLogin")){
                            if (AccountService.getInstance().isLogin()){
                                this.jumpToDynamic(pageParam);
                            }else {
                                AccountService.getInstance().jumpToLogin();
                            }
                        }else {
                            this.jumpToDynamic(pageParam);
                        }


                        break;
                    case TFBridgeTypePrivateMsgList:
                        Intent privateIntent = new Intent(mWXSDKInstance.getContext(), PersonalSendLetterActivity.class);
                        mWXSDKInstance.getContext().startActivity(privateIntent);
                        break;
                    case TFBridgeTypeCartoonDetail:
                        jumpToCartoonDetail(pageParam);
                        break;
                    case TFBridgeTypeNomalDetail:
                        jumpToNomalDetail(pageParam);
                        break;
                    case TFBridgeTypePrivateMsg:
                        jumpToPrivateMsg(pageParam);
                        break;
                    case TFBridgeTypeNovelSweepDetail:
                        jumpToSweepDetail(pageParam);
                        break;
                    case TFBridgeTypeGame:
                        new StartActivityUtils(mWXSDKInstance.getContext(), null).toSquareActivity();
                        break;
                    case TFBridgeTypeReadComic:
                        readComic(pageParam);
                        break;
                    case TFBridgeTypeTag:
                        jumpToTag(pageParam);
                        break;
                    case TFBridgeTypePersonalInfo:
                        break;
                    case TFBridgeTypeMyActivity:
                        if (AccountService.getInstance().isLogin()) {
                            Intent intent2 = new Intent(mWXSDKInstance.getContext(), PersonalNewDynamicActivity.class);
                            intent2.putExtra(Constant.UID, AccountService.getInstance().getUserUid());
                            mWXSDKInstance.getContext().startActivity(intent2);
                        } else {
                            AccountService.getInstance().jumpToLogin();
                        }
                        break;
                    case TFBridgeTypeMyFans:
                        if (AccountService.getInstance().isLogin()) {
                            Intent intent = new Intent(mWXSDKInstance.getContext(), PersonalFansActivity.class);
                            intent.putExtra(Constant.UID, AccountService.getInstance().getUserUid());
                            mWXSDKInstance.getContext().startActivity(intent);
                        } else {
                            AccountService.getInstance().jumpToLogin();
                        }
                        break;
                    case TFBridgeTypeMyAttentions:
                        if (AccountService.getInstance().isLogin()) {
                            Intent attentIntent = new Intent(mWXSDKInstance.getContext(), PersonalAttentionsActivity.class);
                            attentIntent.putExtra(Constant.UID, AccountService.getInstance().getUserUid());
                            mWXSDKInstance.getContext().startActivity(attentIntent);
                        } else {
                            AccountService.getInstance().jumpToLogin();
                        }
                        break;
                    case TFBridgeTypePublishBBS:
                        if (AccountService.getInstance().isLogin()) {
                            Intent bbsIntent = new Intent(mWXSDKInstance.getContext(), MySpeakerActivity.class);
                            mWXSDKInstance.getContext().startActivity(bbsIntent);
                        } else {
                            AccountService.getInstance().jumpToLogin();
                        }
                        break;
                    case TFBridgeTypeSetting:
                        Intent setIntent = new Intent(mWXSDKInstance.getContext(), MoreSetActivity.class);
                        mWXSDKInstance.getContext().startActivity(setIntent);
                        break;
                    case TFBridgeTypePublishProduction:
                        MyWorksActivity.startActivity(mWXSDKInstance.getContext());
                        break;
                    case TFBridgeTypeMyBean:
                        if (AccountService.getInstance().isLogin()) {
                            mWXSDKInstance.getContext().startActivity(new Intent(mWXSDKInstance.getContext(), PersonalPointsActivity.class));
                        } else {
                            AccountService.getInstance().jumpToLogin();
                        }
                        break;
                    default:
                    {
                        Toast.makeText(QLXGlobal.getApplication(), "请升级新版本体验该功能", Toast.LENGTH_SHORT).show();
                    }
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void moreJump(JSONObject pageParam) {

        DfhomeNovelAdapter3.goToNovelMoreActivity(mWXSDKInstance.getContext(),pageParam.getString("moreUrl"),pageParam.getString("title"),"");
    }

    private void bannerJump(JSONObject pageParam) {
        DFHomeBannerBean bean = JSONObject.parseObject(pageParam.toString(), DFHomeBannerBean.class);
        StartActivityUtil.bannerOnclick(mWXSDKInstance.getContext(),bean);
    }

    private void jumpToTag(JSONObject pageParam) {
        DfhomeNovelAdapter3.goToTagActivity(mWXSDKInstance.getContext(),pageParam.getString("tag"),"");
    }

    private void jumpToAlbums(JSONObject pageParam) {
        AlbumsBean bean = JSONObject.parseObject(pageParam.toString(), AlbumsBean.class);
        StartActivityUtil.albumsOnclick(mWXSDKInstance.getContext(), bean);
    }

    private void readComic(JSONObject pageParam) {
        CartoonBean bean=JSONObject.parseObject(pageParam.getJSONObject("topic").toString(),CartoonBean.class);
        CartoonServices.enterCartoonScanNewActivity(mWXSDKInstance.getContext(), bean.getId(), -1,false);
    }

    public void jumpToCartoonDetail(JSONObject pageParam) {
        if (pageParam == null) {
            return;
        }
        String  id = pageParam.getString("object_id");
        Intent intent = new Intent();
        intent.putExtra(Constant.CARTOON_ID, id);
        new StartActivityUtils(mWXSDKInstance.getContext(), intent).toCartoonDesActivity(id);
    }

    public void jumpToNomalDetail(JSONObject pageParam) {
        if (pageParam == null) {
            return;
        }
        String id = pageParam.getString("object_id");
        PersonalNoteService.getInstance().enterPersonalNoteDesActivity(mWXSDKInstance.getContext(), id, "41");

    }

    public void jumpToPrivateMsg(JSONObject pageParam) {
        if (pageParam == null) {
            return;
        }
        String userId = pageParam.getString("userId");
        String nickName = pageParam.getString("nickName");
        String headImage = pageParam.getString("headImage");
        StartWeexActivityUtils.startPrivateMsgActivity(mWXSDKInstance.getContext(),userId,
                nickName);
    }

    public void jumpToSweepDetail(JSONObject pageParam) {
        if (pageParam == null) {
            return;
        }
        String object_id = pageParam.getString("object_id");

        Intent intent = new Intent(mWXSDKInstance.getContext(), SweepFlowerActivity.class);
        intent.putExtra(Constant.SWEEP_ID, object_id);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mWXSDKInstance.getContext().startActivity(intent);
    }

    public void handleAtUser(final JSCallback callback){
        try {
            DiaobaoBaseActivity activity = (DiaobaoBaseActivity) this.mWXSDKInstance.getContext();
            Intent intent = new Intent(activity, PersonalSendLetterActivity.class);
            intent.putExtra("TYPE", "fromNewUgc");

            activity.activityListener = new DiaobaoBaseActivity.TFActivityListener() {
                @Override
                public void onActivityResult(int requestCode, int resultCode, Intent data) {
                    if (requestCode == TFAtResult){
                        if (data != null){
                            String nikename = data.getStringExtra("user_nikename");
                            if (nikename instanceof String){
                                HashMap res = new HashMap();
                                res.put("nickName",nikename);
                                if (callback != null){
                                    callback.invoke(res);
                                }
                            }
                        }
                    }
                }
            };
            activity.startActivityForResult(intent,TFAtResult);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @WXModuleAnno(moduleMethod = true, runOnUIThread = true)
    public void systemShare(String title, String desc) {
        ShareUtil.Companion.shareText(mWXSDKInstance.getContext(),title,desc);
    }

    @WXModuleAnno(moduleMethod = true,runOnUIThread = true)
    public void comicReadLastIndex(String data, JSCallback callback) {
        try {
            JSONObject param = JSON.parseObject(data);
            String id = param.getString("id");
            Read_HirstoryUtil read_hirstoryUtil = new Read_HirstoryUtil(mWXSDKInstance.getContext());
            Map<String, String> historyMap;
            historyMap = read_hirstoryUtil.queryCartoonHirstory(id);
            int readedEposidePos = 0;
            if (historyMap != null && historyMap.size() > 0) {
                readedEposidePos = Integer.valueOf(historyMap.get(id));
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("index", readedEposidePos);
            callback.invoke(jsonObject.toString());
        } catch (Exception e) {

        }
    }


    @JSMethod
    public void setupLoginSuccessInfo(String jsonParam, JSCallback callback) {
        AccountService.setAccountData(jsonParam,callback);
    }

    @JSMethod
    public void getThirdLoginToken(String jsonParam, final JSCallback callback) {
        try {
            JSONObject param = JSON.parseObject(jsonParam);
            final int type = param.getInteger("type");
            if (type == 0) {
                WeiboService.getInstance().ssoAuthorize((Activity) mWXSDKInstance.getContext(), new ILoginCallback() {
                    @Override
                    public void token(String token,String openId,String msg) {
                        login(token, openId, msg,type,callback);
                    }
                });
            } else if (type == 1) {
                QQService.getInstance().login((Activity) mWXSDKInstance.getContext(), new ILoginCallback() {
                    @Override
                    public void token(String token, String openId, String msg) {
                        login(token, openId, msg,type,callback);
                    }
                });
            } else if (type == 2) {
                WXEntryActivity.Companion.setPageType(WXEntryActivity.PAGE_TYPE_WEEX_WECHAT);
                WXEntryActivity.Companion.setOpType(WXEntryActivity.OP_TYPE_LOGIN_WECHAT);
                WeChatService.getInstance(mWXSDKInstance.getContext()).sendWeChatLogin();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void login(String token, String openId, String msg,int type, JSCallback callback) {
        HashMap<String, Object> data = new HashMap<>();
        data.put("type", String.valueOf(type));
        data.put("message", msg);
        HashMap<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("openId", openId);
        data.put("data", map);
        data.put("appKey", Constant.APP_KEY);
        callback.invoke(data);
    }

    @WXModuleAnno(moduleMethod = true,runOnUIThread = true)
    public void closePage(String jsonParam , JSCallback callback){
        try {
            if (jsonParam instanceof String){
                JSONObject param = JSON.parseObject(jsonParam);

                String url = param.getString("url");
                if (url.indexOf("present") > 0){
                    Context context = mWXSDKInstance.getContext();
                    if (context instanceof DiaobaoBaseActivity){
                        DiaobaoBaseActivity activity = (DiaobaoBaseActivity)context;
                        activity.removeWeexView(mWXSDKInstance);
                    }
                }
                if (mWXSDKInstance.getContext() instanceof  Activity){
                    ((Activity) mWXSDKInstance.getContext()).finish();
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    @WXModuleAnno(moduleMethod = true,runOnUIThread = true)
    public void uid(JSCallback callback){
        String uid = AccountService.getInstance().getUserUid();
        if (callback != null){
            HashMap param = new HashMap();
            param.put("uid",Integer.valueOf(uid));
            callback.invoke(param);
        }
    }

    @JSMethod
    public void googlePay(String pID,int option_id) {
        Context context = mWXSDKInstance.getContext();
        if (context instanceof TFWXActivity) {
            ((TFWXActivity)context).googlePay(pID,option_id);
        }
    }

    @JSMethod
    public void initGooglePlay() {
        if (GlobalConfig.isGooglePlay){
            Context context = mWXSDKInstance.getContext();
            if (context instanceof DiaobaoBaseActivity) {
                ((DiaobaoBaseActivity)context).initGooglePay();
            }
        }
    }

    @JSMethod
    public void isGooglePlay(JSCallback callback) {
        if (callback != null) {
            HashMap param = new HashMap();
            param.put("state", GlobalConfig.isGooglePlay);
            callback.invoke(param);
        }
    }

    @WXModuleAnno(moduleMethod = true,runOnUIThread = true)
    public void novelReadLastIndex(String jsonParam , final JSCallback callback){
           //test
        if (callback != null){
            JSONObject param = JSON.parseObject(jsonParam);
            final JSONObject res = new JSONObject();
            final com.alibaba.fastjson.JSONArray ids = param.getJSONArray("ids");
            if (ids!=null){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i=0;i<ids.size();i++) {
                            Integer id = ids.getInteger(i);
                            Read_DataBaseUtil  read_dataBaseUtil = new Read_DataBaseUtil(mWXSDKInstance.getContext());
                            ReadRecord record = read_dataBaseUtil.queryHistoryInfo(id.toString());
                            if (record != null){
                                res.put(id.toString(),record.getPosition() - 1);
                            }
                        }
                        mWXSDKInstance.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                JSONObject data = new JSONObject();
                                data.put("indexs", res);
                                callback.invoke(data.toString());
                            }
                        });
                    }
                }).start();
            }else{
                final String id = param.getString("id");
                if (!TextUtils.isEmpty(id)) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Read_DataBaseUtil  read_dataBaseUtil = new Read_DataBaseUtil(mWXSDKInstance.getContext());
                            ReadRecord record = read_dataBaseUtil.queryHistoryInfo(id);
                            int pos = 0;
                            if (record != null){
                                pos = record.getPosition() ;
                            }
                            final int finalPos = pos;
                            mWXSDKInstance.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    JSONObject data = new JSONObject();
                                    data.put("index", finalPos);
                                    callback.invoke(data.toString());
                                }
                            });
                        }
                    }).start();
                }else{
                    JSONObject data = new JSONObject();
                    data.put("indexs", res);
                    callback.invoke(data.toString());
                }
            }
        }
    }
//    WX_EXPORT_METHOD(@selector(openPageAlive:callback:))
    @WXModuleAnno(moduleMethod = true,runOnUIThread = true)
    public void openPageAlive(String jsonParam , final JSCallback callback){
        this.openPage(jsonParam, new JSCallback() {
            @Override
            public void invoke(Object data) {
                if (callback != null){
                    callback.invokeAndKeepAlive(data);
                }
            }
            @Override
            public void invokeAndKeepAlive(Object data) {
                if (callback != null){
                    callback.invokeAndKeepAlive(data);
                }
            }
        });
    }

    @WXModuleAnno(moduleMethod = true,runOnUIThread = true)
    public void openPageKeep(String jsonParam , final JSCallback callback){
        this.openPageAlive(jsonParam,callback);
    }
    @WXModuleAnno(moduleMethod = true,runOnUIThread = true)
    public void statistics(String eventName){
        TMAnalysis.event(mWXSDKInstance.getContext(), eventName);
    }

    @WXModuleAnno(moduleMethod = true,runOnUIThread = true)
    public void openUrl(String url){
        try {
            if (url instanceof String){

                if (url.indexOf("needLogin") > 0){
                    if (AccountService.getInstance().isLogin() == false) {
                        AccountService.getInstance().jumpToLogin();
                        return ;
                    }
                }

                HashMap<String, Object> param = new HashMap<String, Object>();
                param.put("url",url);

                Map dataParam = null;

                try {
                    JSONObject config = JSON.parseObject(url);
                    if(config != null && config.containsKey("url")){
                        String urlStr = config.getString("url");
                        url = urlStr;
                        JSONObject data = null;
                        if(config.containsKey("data")){
                            data = config.getJSONObject("data");
                        }else if(config.containsKey("param")){
                            data = config.getJSONObject("param");
                        }
                        dataParam = data;

                        param.put("url",urlStr);
                        param.put("data",data);
                    }
                }catch (Exception e){

                }
                if (url instanceof String){
                    if (url.indexOf("present") > 0){
                        if (mWXSDKInstance.getContext() instanceof TFWXActivity) {
                            TFWXActivity ac = (TFWXActivity) mWXSDKInstance.getContext();
                            ac.presentWeexView(url, dataParam);
                        }else if(mWXSDKInstance.getContext() instanceof DiaobaoBaseActivity){
                            DiaobaoBaseActivity activity = (DiaobaoBaseActivity)mWXSDKInstance.getContext();
                            activity.presentWeexView(url, dataParam);
                        }
                        return;
                    }
                }
                QLXApplicationUtil.pushActivity((Activity) mWXSDKInstance.getContext(), TFWXActivity.class,param);

            }
        }catch (Exception e){
            e.printStackTrace();
        }


    }

    @WXModuleAnno(moduleMethod = true,runOnUIThread = true)
    public void openURL(String url){
         this.openUrl(url);


    }

    @WXModuleAnno(moduleMethod = true,runOnUIThread = true)
    public void addKeyboardShow(final JSCallback callback){

        QLXKeyBoard.addKeyboardListener((Activity) this.mWXSDKInstance.getContext(), new QLXKeyBoard.QLXKeyBoardListener() {
            @Override
            public void keyBoardShow(int height) {
                if (callback != null){
                    HashMap param = new HashMap();
                    String value = QLXStringUtil.pxToDp(height) + "wx";
                    param.put("height",value);
                    callback.invokeAndKeepAlive(param);
                }
            }
            @Override
            public void keyBoardHide(int height) {
            }
        });

    }

    @WXModuleAnno(moduleMethod = true,runOnUIThread = true)
    public void addKeyboardHide(final JSCallback callback){
        QLXKeyBoard.addKeyboardListener((Activity) this.mWXSDKInstance.getContext(), new QLXKeyBoard.QLXKeyBoardListener() {
            @Override
            public void keyBoardShow(int height) {
            }

            @Override
            public void keyBoardHide(int height) {
                if (callback != null){
                    HashMap param = new HashMap();
                    param.put("height",Integer.valueOf(height));
                    callback.invokeAndKeepAlive(param);
                }
            }
        });
    }

    @WXModuleAnno(moduleMethod = true,runOnUIThread = true)
    public void pickImage(String count ,final JSCallback callback){
        this.count = Integer.valueOf(count);
        this.callback = callback;
        isCrop = false;
//        selectImage();
//        ImagePickUtil.pickImage((DiaobaoBaseActivity) mWXSDKInstance.getContext(),Integer.valueOf(count),false,callback);

    }


    @JSMethod
    public void pickImage2(String params ,final JSCallback callback){
        try {
            JSONObject jsonObject = JSON.parseObject(params);
             count = 1;
            if (jsonObject.containsKey("count")) {
                count = jsonObject.getInteger("count");
            }
             cropType = ImagePickUtil.CROP_TYPE_CIRCLE;// 默认圆形
            if (jsonObject.containsKey("cropType")) {
                cropType = jsonObject.getInteger("cropType");
            }
             isCrop = true;
            if (jsonObject.containsKey("isCrop")){
                isCrop = jsonObject.getBoolean("isCrop");
            }
            width = jsonObject.getInteger("width");
            height = jsonObject.getInteger("height");
            this.callback = callback;
//            selectImage();
        }catch (Exception e){
            Toast.makeText(WeMediaApplication.applicationContext,"操作失败",Toast.LENGTH_LONG).show();
        }
    }
    int width;
    int height;
    int cropType;
    boolean isCrop;
    int count;
    JSCallback callback;
    protected final void selectImage() {
        String[] selectPicTypeStr = {"拍照", "相册"};
        AlertDialog dialog = new AlertDialog.Builder((DiaobaoBaseActivity) mWXSDKInstance.getContext()).setItems(selectPicTypeStr, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    // 相机拍摄
                    case 0:
                        if(ContextCompat.checkSelfPermission(mWXSDKInstance.getContext(), Manifest.
                                permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
                            PermissionTipDialog dialog1 = new PermissionTipDialog(mWXSDKInstance.getContext());
                            dialog1.show();
                            dialog1.setPre("摄像头权限");
                            dialog1.setContent("用于添加上传头像图片等场景");
                            dialog1.setOnBtnClickListener(() -> {
                                ActivityCompat.requestPermissions((DiaobaoBaseActivity) mWXSDKInstance.getContext(), new
                                        String[]{ Manifest.permission.CAMERA}, 1);
                            });
                        }else {
                            ImagePickUtil.pickCamera((DiaobaoBaseActivity) mWXSDKInstance.getContext(),count,isCrop,cropType,width,height,callback);
                        }
                        break;
                    // 手机相册
                    case 1:
                        if(ContextCompat.checkSelfPermission(mWXSDKInstance.getContext(), Manifest.
                                permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                            PermissionTipDialog dialog1 = new PermissionTipDialog(mWXSDKInstance.getContext());
                            dialog1.show();
                            dialog1.setPre("相册权限");
                            dialog1.setContent("用于添加上传头像图片等场景");
                            dialog1.setOnBtnClickListener(() -> {
                                ActivityCompat.requestPermissions((DiaobaoBaseActivity) mWXSDKInstance.getContext(), new
                                        String[]{ Manifest.permission.CAMERA}, 2);
                            });
                        }else {
                            ImagePickUtil.pickImage((DiaobaoBaseActivity) mWXSDKInstance.getContext(),count,isCrop,cropType,width,height,callback);
                        }
                        break;
                    default:
                        break;
                }

            }
        }).show();

        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {

            }
        });
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    ImagePickUtil.pickCamera((DiaobaoBaseActivity) mWXSDKInstance.getContext(),count,isCrop,cropType,width,height,callback);
                }else{
                    Toast.makeText((DiaobaoBaseActivity) mWXSDKInstance.getContext(), "You denied the permission", Toast.LENGTH_SHORT).show();
                }
                break;
            case 2:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    ImagePickUtil.pickImage((DiaobaoBaseActivity) mWXSDKInstance.getContext(),count,isCrop,cropType,width,height,callback);
                }else{
                    Toast.makeText((DiaobaoBaseActivity) mWXSDKInstance.getContext(), "You denied the permission", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }


    @WXModuleAnno(moduleMethod = true,runOnUIThread = true)
    public void uploadImage(String url ,final JSCallback callback){

        Bitmap image = ImageUtil.getimage(url);
        final int width = image.getWidth();
        final int height = image.getHeight();

        ImageManager.uploadImage(url, new UploadImageListener() {
            @Override
            public void onPath(String url) {
//                block(@{@"url":url,@"width":@(width),@"height":@(image.size.height)});
                HashMap res = new HashMap();
                res.put("url",url);
                res.put("width",width);
                res.put("height",height);
                if (callback != null){
                    callback.invoke(res);
                }

            }
        });

    }
    @WXModuleAnno(moduleMethod = true,runOnUIThread = true)
    public void imageBrowse(String param){
        if (param instanceof String){

            try {
                JSONObject info = JSON.parseObject(param);
                com.alibaba.fastjson.JSONArray list = info.getJSONArray("images");
                int index = 0;
                if(info.containsKey("index")){
                    index = info.getInteger("index");
                }
                ArrayList<String> images = new ArrayList<String>();
                for (int i = 0; i < list.size(); i++){
                    images.add(list.getString(i));
                }
                ShowPicActivity.showPic(this.mWXSDKInstance.getContext(),images,index);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }


    @JSMethod
    public void openNovel(String novelId,JSCallback callback) {
        String key = "TFOffLineCache_" + AccountService.getInstance().getUserUid() + "_" + novelId;
        Intent intent = new Intent(mWXSDKInstance.getContext(), NovelSectionDetailsActivity.class);
        intent.putExtra(NovelSectionDetailsActivity.INTENT_KEY_OFFLINE_BOOK_KEY, key);
        mWXSDKInstance.getContext().startActivity(intent);
    }





    //--------------------------我是分割线------------------------------

    // 页面跳转

    private void jumpToComment(JSONObject pageParam){

        try {
            HomeTopBean topicBean = new HomeTopBean();
            ;
            org.json.JSONObject topic = new org.json.JSONObject(pageParam.toString());
            topicBean.setJson2(topic);
            Intent intent = new Intent(mWXSDKInstance.getContext(), NovelDesToCommActivity.class);
            intent.putExtra(Constant.NOVEL_HOME_BEAN, topicBean);
            if (topicBean != null) {
                intent.putExtra(Constant.AUTHOR_ID, topicBean.getUser().getUserId());
            }

            intent.putExtra(Constant.FLOWERSHOWFLAG, Constant.FLOWER_HIDE);
            intent.putExtra(Constant.TOPIC, topicBean.getId());
            mWXSDKInstance.getContext().startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private  void  jumpToNovelCatalog(JSONObject pageParam){
        String id = pageParam.getString("id");
        if (pageParam.containsKey("object_type")&&
                Constant.OBJECT_TYPE_CARTOON == pageParam.getInteger("object_type")) {
            CartoonServices.enterCartoonEpisodeMenu(mWXSDKInstance.getContext(), id);
            return;
        }
        Intent intent = new Intent(mWXSDKInstance.getContext(), NovelDesToDetailActivity.class);
        intent.putExtra(NovelDesToDetailActivity.ARTICLEID, id);
        mWXSDKInstance.getContext().startActivity(intent);
    }

    private  void  jumpToPersonalCenter(JSONObject pageParam){
        UserDetailActivity.Companion.startActivity(mWXSDKInstance.getContext(),pageParam.getString("uid"));
    }

    private  void  jumpToDynamic(JSONObject pageParam){
        Intent intent = null;
        int object_type = pageParam.getIntValue("object_type");
        if (object_type == 38){
            intent = new Intent(mWXSDKInstance.getContext(), NewCpDesActivity.class);
            if (pageParam.containsKey("id")){
                intent.putExtra(Constant.TOPIC_ID, pageParam.getString("id"));
            }
            if (pageParam.containsKey("name")){
                intent.putExtra(Constant.KEY_SEARCH_TAG, pageParam.getString("name"));
            }

            intent.putExtra(Constant.TYPE, NewCpDesActivity.TYPE_TAG);
            mWXSDKInstance.getContext().startActivity(intent);
        }else {
            if (pageParam.containsKey("url")){
                intent = new Intent(mWXSDKInstance.getContext(),BrowseActivity.class);
                intent.putExtra("URL",pageParam.getString("url"));
                mWXSDKInstance.getContext().startActivity(intent);
            }
        }
    }

    private void jumpToNovel(final JSONObject pageParam){
        String articleId = pageParam.getJSONObject("topic").getString("id");
        boolean has_fav = false;
        int month_ticket_sum = 0;
        try {
            JSONObject jsonObject = pageParam.getJSONObject("topic");
            if (jsonObject != null) {
                has_fav = jsonObject.getBoolean("has_fav");
                month_ticket_sum = jsonObject.getInteger("month_ticket_sum" );
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        Read_DataBaseUtil  read_dataBaseUtil = new Read_DataBaseUtil(mWXSDKInstance.getContext());
        ReadRecord record = read_dataBaseUtil.queryHistoryInfo(articleId);

        Intent intent = new Intent(mWXSDKInstance.getContext(), NovelSectionDetailsActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (record != null) {
            intent.putExtra(Constant.ARTICLE_ID, record.getSection_id());
        }
        intent.putExtra(Constant.ARTICLE_NOVELID, articleId);
        intent.putExtra("activity", "NovelDesActivity");
        intent.putExtra(Constant.HAS_FAV,  has_fav);
        intent.putExtra(Constant.MONTH_TICKET_SUM,  month_ticket_sum);
        mWXSDKInstance.getContext().startActivity(intent);

    }

    private void jumpToNovelChanpterList(JSONObject pageParam){
        Intent intent = new Intent(mWXSDKInstance.getContext(), NewNovelCreateListTosActivity.class);

        String novelId = pageParam.getString("id");
        String novelName = pageParam.getString("title");
        intent.putExtra(Constant.NOVEL_ID, novelId);
        intent.putExtra(Constant.NOVEL_NAME, novelName);
        mWXSDKInstance.getContext().startActivity(intent);
    }


    private void jumpToCartoonShare(JSONObject pageParam) {
        try {
            ShareTopPopupWindow menuWindow = new ShareTopPopupWindow((Activity) mWXSDKInstance.getContext());
            CartoonBean bean=JSONObject.parseObject(pageParam.getJSONObject("object").toString(),CartoonBean.class);
            if (bean == null) {
                return;
            }
            ShareBeansInfo shareInfo = new ShareBeansInfo(bean.getId(), bean.getTitle(), bean.getImage(), bean.getShare_url(), ShareBeansInfo.CARTOON_SHARE_FLAG);
            shareInfo.setDescription(bean.getIntro());
            HomeTopBean homeTopBean = new HomeTopBean();
            if (bean.getUser() != null) {
                homeTopBean = new HomeTopBean();
                homeTopBean.setAuthor(bean.getUser().getName());
            }
            shareInfo.setShareData(homeTopBean);

            String[] tagStrings = bean.getTag_list().split("\\s+");
            if (tagStrings != null && tagStrings.length > 0)
            {
                shareInfo.setTags(tagStrings);
            }
            menuWindow.setShareBeans(shareInfo);
            int x = pageParam.getIntValue("x");
            int y = pageParam.getIntValue("y");
            int type = pageParam.getIntValue("type");
            if (type == 99){
                menuWindow.showAtLocation(mWXSDKInstance.getRootView(), Gravity.CENTER,x, y); // 设置layout在PopupWindow中显示的位置
            }else if(type == 101){
                shareInfo.setSocial_type(101);
                menuWindow.shareToSinalWeibo(shareInfo);
            }else if(type == 102){
                shareInfo.setSocial_type(102);
                menuWindow.shareToWeixin(shareInfo);
            }else if(type == 104){
                shareInfo.setSocial_type(104);
                menuWindow.shareQQ(shareInfo);
            }else if(type == 1){

            }
        } catch (Exception e) {

        }
    }

    private void jumpToNovelShare(JSONObject pageParam){
        try {
            ShareTopPopupWindow menuWindow = new ShareTopPopupWindow((Activity) mWXSDKInstance.getContext());
            HomeTopBean topicBean = new HomeTopBean();
            ;
            String jsonString = pageParam.getJSONObject("object").toString();
            org.json.JSONObject topic = new org.json.JSONObject(jsonString);
            topicBean.setJson2(topic);
            String imageUrl = "";
            if (topicBean.getImages()!=null && topicBean.getImages().length > 0) {
              imageUrl = topicBean.getImages()[0].getImgUrl();
            }
            ShareBeansInfo shareInfo = new ShareBeansInfo(topicBean.getId(), topicBean.getTitle(), imageUrl, topicBean.getShareUrl(), ShareBeansInfo.NOVEL_SHARE_FLAG);
            shareInfo.setShartText(topicBean.getDes());
            shareInfo.setArticleAuthor(topicBean.getAuthor());
            shareInfo.setShareData(topicBean);

            String[] tagStrings = null;
            TagsBean[] titleLabels = topicBean.getTags();
            if (titleLabels != null && titleLabels.length != 0) {
                tagStrings = new String[titleLabels.length];
                for (int i = 0; i < titleLabels.length; i++) {
                    tagStrings[i] = titleLabels[i].getName();
                }
            }
            if (tagStrings != null && tagStrings.length > 0) {
                shareInfo.setTags(tagStrings);
            }
            menuWindow.setShareBeans(shareInfo);
            int x = pageParam.getIntValue("x");
            int y = pageParam.getIntValue("y");
            int type = pageParam.getIntValue("type");
            if (type == 99){
                menuWindow.showAtLocation(mWXSDKInstance.getRootView(), Gravity.CENTER, x,y); // 设置layout在PopupWindow中显示的位置
            }else if(type == 101){
                shareInfo.setSocial_type(101);
                menuWindow.shareToSinalWeibo(shareInfo);
            }else if(type == 102){
                shareInfo.setSocial_type(102);
                menuWindow.shareToWeixin(shareInfo);
            }else if(type == 104){
                shareInfo.setSocial_type(104);
                menuWindow.shareQQ(shareInfo);
            }else if(type == 1){

            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @WXModuleAnno(moduleMethod = true,runOnUIThread = true)
    public void setNightMode(){
        WeMediaApplication.getInstance().saveDayMode();
        EventBusChangeTheme event = new EventBusChangeTheme();
        event.setTag(EventBusChangeTheme.TAG_CHANGE_THEME);
        event.setDay(false);
        EventBus.getDefault().post(event);
        ((DiaobaoBaseActivity)mWXSDKInstance.getContext()).updateStatusBar();
    }


    @WXModuleAnno(moduleMethod = true, runOnUIThread = true)
    public void setDayMode() {
        WeMediaApplication.getInstance().saveDayMode();
        EventBusChangeTheme event = new EventBusChangeTheme();
        event.setTag(EventBusChangeTheme.TAG_CHANGE_THEME);
        event.setDay(true);
        EventBus.getDefault().post(event);
        ((DiaobaoBaseActivity)mWXSDKInstance.getContext()).updateStatusBar();
    }



    @WXModuleAnno(moduleMethod = true,runOnUIThread = true)
    public void isNightMode(JSCallback callback){
        HashMap<String, Boolean> map = new HashMap<>();
        map.put("value", WeMediaApplication.getInstance().isDayNightMode_Night);
        callback.invoke(map);
    }

    @WXModuleAnno(moduleMethod = true,runOnUIThread = true)
    public void share(String data) {
        ShareUtils.thirdPartyShare(mWXSDKInstance.getContext(),data,true);
    }

    private void jumpToFlower(JSONObject pageParam){
        try {
            HomeTopBean topicBean = new HomeTopBean();
            String jsonString = pageParam.toString();
            org.json.JSONObject topic = new org.json.JSONObject(jsonString);
            topicBean.setJson2(topic);
            Map<String , String> map = new HashMap<>();
            map.put("mid" , topicBean.getId());
            map.put("mtype" , topicBean.getObject_type());
            try {// Unable to add window -- token null is not valid; is your activity running?
                FlowerDialogManager.getInstance(mWXSDKInstance.getContext() , topicBean,topicBean.getShareUrl());
            }catch (Exception e){
                e.printStackTrace();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void jumpToReward(JSONObject pageParam){
        try {
            if(pageParam.containsKey("object_type") &&
                    pageParam.getString("object_type").equals(String.valueOf(Constant.OBJECT_TYPE_CARTOON))){
                CartoonBean topicBean = new CartoonBean();
                String jsonString = pageParam.toString();
                org.json.JSONObject topic = new org.json.JSONObject(jsonString);
                topicBean.setJson2(topic);
                GiftDialogManager.getInstance(mWXSDKInstance.getContext() , topicBean);
            }else{
                HomeTopBean topicBean = new HomeTopBean();
                String jsonString = pageParam.toString();
                org.json.JSONObject topic = new org.json.JSONObject(jsonString);
                topicBean.setJson2(topic);
                GiftDialogManager.getInstance(mWXSDKInstance.getContext() , topicBean);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }



    private void jumpToDownloadNovel(JSONObject pageParam){
        if (!AccountService.getInstance().isLogin()) {
            AccountService.getInstance().jumpToLogin();
            return;
        }
        boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (!sdCardExist) {
            UIUtil.toastMessage(mWXSDKInstance.getContext(), "SD卡异常");
            return;
        }
        String articleId = pageParam.getString("id");
        if (pageParam.containsKey("title")){
            mArticleTitle = pageParam.getString("title");
        }
        mArticleId = articleId;
        List<String> offLineIds = (new OffLineDataBaseUtil(mWXSDKInstance.getContext())).queryNovelId();
        if (offLineIds.contains(articleId)) {
            UIUtil.toastMessage(mWXSDKInstance.getContext(), "已经在“离线小说”列表里啦");
            return;
        }


        File file = new File(Constant.AppDir.DIR_OFFLINE_DATA);
        if (!file.exists()) {
            file.mkdir();
        }

        HomeMainServices.getInstance().loadNovel(this, articleId);
    }


    @Override
    public void handleResponse(int handleType, HttpResponseObject response) {
        if (response.getStatus() == 0) {
                        try {
                            org.json.JSONObject downObject = (org.json.JSONObject) response.getData();
                            int score = downObject.getJSONObject("score_result").getInt("score");
                            if (score == 0) {
                                UIUtil.toastMessage(mWXSDKInstance.getContext(), "你已下载过此小说  再次下载不需扣豆子");
                            } else {
                                UIUtil.toastMessage(mWXSDKInstance.getContext(), "开始下载" + score + "豆子");
                            }
                            Intent serviceIntent = new Intent(mWXSDKInstance.getContext(), OffLineService.class);
                            String down_url = downObject.getString("url");// "http://m.doufushe.com/doufu/novel/"+articleId+".json.xz";

                            OffLineInfoBean offLineInfoBean = new OffLineInfoBean(down_url, mArticleTitle, Constant.OffLineSTATUS.DOWN_START, System.currentTimeMillis() / 1000 + "", mArticleId);
                            serviceIntent.putExtra("offline", offLineInfoBean);
                            // insert


                            (new OffLineDataBaseUtil(mWXSDKInstance.getContext())).insert(down_url, mArticleTitle, mArticleId, Constant.OffLineSTATUS.DOWN_START, System.currentTimeMillis() / 1000 + "");

                            // read_dataBaseUtil.insert(articleId, "", 0, 0, "",
                            // System.currentTimeMillis() / 1000+ "");
                            mWXSDKInstance.getContext().startService(serviceIntent);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        UIUtil.toastMessage(mWXSDKInstance.getContext(), DiaobaoUtil.getErrorTips(response));

                    }
    }

    @JSMethod
    public void getBottomStatusHeight(JSCallback jsCallback){
        try {
            int height = ScreenUtil.getBottomStatusHeight(mWXSDKInstance.getContext());
            if (jsCallback != null) {
                HashMap<String,Integer> map = new HashMap();
                if(height>40){
                    map.put("height", height-40);
                }else{
                    map.put("height", height);
                }
                jsCallback.invokeAndKeepAlive(map);
            }
        }catch (Exception e){

        }
    }

    @JSMethod
    public void getTitleHeight(JSCallback jsCallback){
        try {
            int height = ScreenUtil.getTitleHeight((Activity) mWXSDKInstance.getContext());
            if (jsCallback != null) {
                jsCallback.invokeAndKeepAlive(height);
            }
        }catch (Exception e){
        }
    }

    @JSMethod
    public void getStatusHeight(JSCallback jsCallback){
        try {
            int height = ScreenUtil.getStatusHeight(mWXSDKInstance.getContext());
            if (jsCallback != null) {
                jsCallback.invokeAndKeepAlive(height);
            }
        }catch (Exception e){
        }
    }


    @JSMethod
    public void thirdPartyRecharge(String json) {
        try {
            org.json.JSONObject object = new org.json.JSONObject(json);
            String charge = object.getString("charge");
            Toast.makeText(mWXSDKInstance.getContext(),"支付失败",Toast.LENGTH_LONG).show();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @JSMethod
    public void weixinPay(String json) {
        WeixinService.getInstance(mWXSDKInstance.getContext()).payRequest(json);
    }

    @JSMethod
    public void aliPay(String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        if (jsonObject != null && jsonObject.containsKey("orderInfo")) {
            String orderInfo = jsonObject.getString("orderInfo");
            AliPayActivity.startActivity(mWXSDKInstance.getContext(),orderInfo);
        }
    }

    @JSMethod
    public void startMiniApp(String json) {
        Toast.makeText(mWXSDKInstance.getContext(),"不支持该功能",Toast.LENGTH_LONG).show();
    }

    @JSMethod
    public void presentInApp(String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        if (jsonObject.containsKey("url")) {
            String url = jsonObject.getString("url");
            if (jsonObject.containsKey("data")) {
                JSONObject data = jsonObject.getJSONObject("data");
                DialogWeexActivity.startActivity(mWXSDKInstance.getContext(),url,data,Intent.FLAG_ACTIVITY_NEW_TASK);
            }else{
                DialogWeexActivity.startActivity(mWXSDKInstance.getContext(),url,Intent.FLAG_ACTIVITY_NEW_TASK);
            }
        }
    }

    @JSMethod
    public void preloadMiniApp() {
    }

    @JSMethod
    public void closeInApp(JSCallback jsCallback) {
        if (mWXSDKInstance.getContext() instanceof  Activity){
            ((Activity) mWXSDKInstance.getContext()).finish();
        }
        if (jsCallback != null) {
            jsCallback.invoke("");
        }
    }

    @JSMethod
    public void jumpToHomePage(String param){
        JSONObject json = JSON.parseObject(param);
        int index = json.getInteger("index");
        Intent intent = new Intent(mWXSDKInstance.getContext(), MainHomeActivity.class);
        intent.putExtra("index", index);
        mWXSDKInstance.getContext().startActivity(intent);
    }


    @JSMethod
    public void isLogin(JSCallback callback) {
        boolean isLogin = AccountService.getInstance().isLogin();
        if (callback != null){
            HashMap param = new HashMap();
            if (isLogin) {
                param.put("state", true);
            }else{
                param.put("state", false);
            }
            callback.invoke(param);
        }
    }

    @JSMethod
    public void setChatNovelRecord(String jsonString){
        JSONObject json = JSON.parseObject(jsonString);
        int id = json.getInteger("id");
        String title = json.getString("title");
        String progress = json.getString("progress");
        Read_DataBaseUtil.updateChatNovelRecord(mWXSDKInstance.getContext(),String.valueOf(id),title,progress);
        ReadRecord record = new ReadRecord();
        record.setType(Constant.OBJECT_TYPE_CHATNOVEL);
        record.setSection_id("");
        record.setNovel_id(String.valueOf(id));
        record.setPosition(0);
        record.setAll_num(0);
        record.setProgress(progress);
        record.setName(title);
        record.setImg_url("");
        ReadHistoryUtil.addOrUpdateData(record);
    }

    @JSMethod
    public void openRecontrollerWithID(String novel){
        JSONObject json = JSON.parseObject(novel);
        int position = json.getInteger("position");
        int id = json.getInteger("id");
        int object_type = json.getInteger("object_type");
        if (object_type == 45){
            CartoonServices.enterCartoonScanNewActivity(mWXSDKInstance.getContext(),String.valueOf(id),position,false);
        }else{
            String section_id = json.getString("section_id");
            Intent intent = new Intent(mWXSDKInstance.getContext(), NovelSectionDetailsActivity.class);
            intent.putExtra(Constant.ARTICLE_ID, section_id);
            intent.putExtra(Constant.ARTICLE_NOVELID,String.valueOf(id));
            mWXSDKInstance.getContext().startActivity(intent);
        }

    }

    @JSMethod
    public void ZLLog(String log) {
        TTLog.d("WEEXLOG",log);
    }

    @JSMethod
    public void ZLLog(String tag,String log) {
        TTLog.d(tag,log);
    }

    @JSMethod
    public void weexLog(String log){
        Log.d("weexLog",log);
    }

    @JSMethod
    public void versionNumWithCallback(JSCallback callback) {
        if (callback != null) {
            callback.invoke(PackageUtils.versionName);
        }
    }

    @JSMethod
    public void WX_AES128Encrypt(String input, String key, String iv, JSCallback jsCallback) {
        if (jsCallback != null) {
            HashMap map = new HashMap();
            map.put("resultStr",AesUtil.encrypt(input, key, iv));
            jsCallback.invoke(map);
        }
    }

    @JSMethod
    public void WX_AES128Decrypt(String input,String key,String iv,JSCallback jsCallback){
        if (jsCallback != null) {
            JSONObject object = new JSONObject();
            object.put("resultStr",AesUtil.desEncrypt(input, key, iv));
            jsCallback.invoke(object);
        }
    }

    @JSMethod
    public void uploadNovelEditData() {
        NovelEditManager.getInstance().uploadAllData();
    }

    @JSMethod
    public void caculateChapterNum(String content,JSCallback jsCallback) {
        if (jsCallback != null) {
            HashMap map = new HashMap();
            if (!TextUtils.isEmpty(content)) {
                int nCount = DiaobaoUtil.getStringSizeNoNull(content);
                map.put("contentLength", nCount);
            }else{
                map.put("contentLength", 0);
            }
            jsCallback.invoke(map);
        }
    }

    @JSMethod
    public void weexAppearVC(String tag){

    }

    @JSMethod
    public void weexClickEvent(String tag){

    }


    @JSMethod
    public void openNovelDetails(String params){
        JSONObject obj = JSON.parseObject(params);
        if (obj.containsKey("id")){
            int id = obj.getIntValue("id");
            NovelDetailsActivity.Companion.startActivity(mWXSDKInstance.getContext(),id);
        }
    }

    @JSMethod
    public void openStoryDetails(String params){
        JSONObject obj = JSON.parseObject(params);
        if (obj.containsKey("id")){
            int id = obj.getIntValue("id");
            StoryDetailsActivity.Companion.startActivity(mWXSDKInstance.getContext(),id);
        }
    }

    @JSMethod
    public void openUserDetails(String params) {
        JSONObject obj = JSON.parseObject(params);
        if (obj.containsKey("uid")) {
            int uid = obj.getIntValue("uid");
            UserDetailActivity.Companion.startActivity(mWXSDKInstance.getContext(),uid);
        }
    }

    @JSMethod
    public void verifyLogin(JSCallback callback) {
//        SimpleWeexActivity.startActivity(mWXSDKInstance.getContext(),"vue/login/TFLoginRegister.js", Intent.FLAG_ACTIVITY_NEW_TASK);

//        NovelDetailsActivity.Companion.startActivity(mWXSDKInstance.getContext(),10874);
        UVerifyManager.getInstance().verifyLogin(callback);
    }


}